package handlers

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"

	"chat-app/internal/app/services"
)

type UserHandler struct {
	userService services.UserService
}

func NewUserHandler(userService services.UserService) *UserHandler {
	return &UserHandler{userService: userService}
}

// GetUserInfo 获取用户信息
func (h *UserHandler) GetUserInfo(c *gin.Context) {
	currentUserID := c.MustGet("userID").(uint)

	userID, err := strconv.ParseUint(c.Param("userID"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
		return
	}

	user, err := h.userService.GetUser(uint(userID))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
		return
	}

	// 对当前用户提供更多信息？
	response := gin.H{
		"id":       user.ID,
		"phone":    user.Phone,
		"nickname": user.Nickname,
	}

	// 对于目标用户，获取好友状态
	if uint(userID) != currentUserID {
		status, _ := h.userService.GetFriendStatus(currentUserID, uint(userID))
		response["friend_status"] = status
	}

	c.JSON(http.StatusOK, response)
}

// SearchUsers 搜索用户
func (h *UserHandler) SearchUsers(c *gin.Context) {
	query := c.Query("q")
	if query == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Search query required"})
		return
	}

	users, err := h.userService.SearchUsers(query)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to search users"})
		return
	}

	c.JSON(http.StatusOK, users)
}

// UpdateNickname 更新用户昵称
func (h *UserHandler) UpdateNickname(c *gin.Context) {
	userID := c.MustGet("userID").(uint)

	var req struct {
		Nickname string `json:"nickname" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	if err := h.userService.UpdateUserNickname(userID, req.Nickname); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update nickname"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Nickname updated"})
}

// GetFriendStatus 获取两个用户之间的好友状态
func (h *UserHandler) GetFriendStatus(c *gin.Context) {
	currentUserID := c.MustGet("userID").(uint)

	targetID, err := strconv.ParseUint(c.Param("targetID"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid target ID"})
		return
	}

	status, err := h.userService.GetFriendStatus(currentUserID, uint(targetID))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": status})
}
